'''
1、pd读取数据
2、选择有影响的特征
3、填补缺失值age
4、数据分割
5、转换成字典，对数据集特征抽取将有类别的特征（票类，性别）变成One-Hot编码形式
x_train.to_dict(orient='records')
6、决策树估计器流程
class sklearn.tree.DecisionTreeClassifier(criterion=’gini’, max_depth=None,random_state=None)
决策树分类器
criterion:默认是’gini’系数，也可以选择信息增益的熵’entropy’
max_depth:树的深度大小
random_state:随机数种子
method:
decision_path:返回决策树的路径

'''
import matplotlib as plt
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction import DictVectorizer
from sklearn.tree import DecisionTreeClassifier, export_graphviz

# 1、pd读取数据
data = pd.read_csv("http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic.txt")

# 2选择有影响的特征
x = data[['pclass', 'age', 'sex']]
y = data[['survived']]

# 3填充缺失值
x['age'].fillna(x['age'].mean(), inplace=True)

# 4数据分割
x_train, x_test, y_train, y_test = train_test_split(x, y)

print(x_train,'111111111111')

# 5、转换成字典，对数据集特征抽取将有类别的特征（票类，性别）变成One-Hot编码形式
# x_train.to_dict(orient='records')
x_train = x_train.to_dict(orient="records")
x_test = x_test.to_dict(orient="records")
print(x_train,'2222222222222')
dv = DictVectorizer()
# 特征名
x_train = dv.fit_transform(x_train)
x_test = dv.transform(x_test)
print(x_train.toarray(),'33333333333')
#
# # print(dv.get_feature_names())
# # print(x_train.toarray())
#
# # 6 决策树估计器流程
#
dtc = DecisionTreeClassifier(criterion="entropy", max_depth=4)
dtc.fit(x_train, y_train)
# 预测
y_predict = dtc.predict(x_test)

score = dtc.score(x_test, y_test)

print(score)

# 导出为决策树
export_graphviz(decision_tree=dtc, out_file='./tree.dot')
